﻿/**
 * Copyright (C) 2013 original author and authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Castle.Core.Interceptor;
using Castle.DynamicProxy;

namespace NGuice.Inject.Spi
{
    /// <summary>
    /// 此类与InvocationHandler接口一样，从java中移植而来，用于C#中实现动态代理。
    /// <remarks>
    /// 将来版本将使用适配器模式！
    /// </remarks>
    /// </summary>
    public class Proxy
    {
        /**
    * the invocation handler for this proxy instance.
    * @serial
    */
        protected InvocationHandler h;

        /**
         * Prohibits instantiation.
         */
        private Proxy()
        {
        }

        /**
         * Constructs a new {@code Proxy} instance from a subclass
         * (typically, a dynamic proxy class) with the specified value
         * for its invocation handler.
         *
         * @param   h the invocation handler for this proxy instance
         */
        protected Proxy(InvocationHandler h)
        {
            this.h = h;
        }

        /// <summary>
        /// 从java中移植构造动态代理类，这里使用DynamicProxy实现动态代理
        /// </summary>
        /// <param name="loader"></param>
        /// <param name="interfaces"></param>
        /// <param name="h"></param>
        /// <returns></returns>
        public static object NewProxyInstance(Type[] interfaces, InvocationHandler handler, Assembly loader = null)
        {
            if (interfaces == null)
                throw new ArgumentNullException("proxy interface must not null");
            Type[] loadInterfaces = new Type[interfaces.Length];
            if (loader != null)
            {
                //重新使用程序集加载类型
                for (int i = 0; i < interfaces.Length; i++)
                {
                    Type t = loader.GetType(interfaces[i].FullName, false);
                    if (t != null)
                        loadInterfaces[i] = t;
                    else
                        loadInterfaces[i] = interfaces[i];
                }
            }
            else
            {
                loadInterfaces = interfaces;
            }

            //使用dynamicProxy实现动态代理
            ProxyGenerator proxyGenerator = new ProxyGenerator();
            return proxyGenerator.CreateInterfaceProxyWithoutTarget(loadInterfaces[0], loadInterfaces, new InvocationHandlerAdapter(handler));
        }
    }

    public class InvocationHandlerAdapter : IInterceptor
    {
        private InvocationHandler handler;

        public InvocationHandlerAdapter(InvocationHandler handler)
        {
            this.handler = handler;
        }

        public void Intercept(IInvocation invocation)
        {
            invocation.ReturnValue = handler.Invoke(invocation.Proxy, invocation.Method, invocation.Arguments);
        }
    }
}
